/**
 * Created by DengYun on 2017/2/25.
 */
import React from 'react';
import { observable, isObservableMap, runInAction } from 'mobx';
import { observer } from 'mobx-react';
import {
  Button, Input as AntdInput, Form, Upload as AntdUpload,
  InputNumber as AntdInputNumber,
} from 'antd';
import camelCase from 'camelcase';
import {get} from "../../logic/api";

function getField(target, field) {
  if (field) {
    if (isObservableMap(target)) {
      // Map
      return target.get(field);
    } else {
      // Object/Array
      return target[field];
    }
  } else {
    // Boxed Value
    return  target.get();
  }
}

function setField(target, field, value) {
  if (field) {
    if (isObservableMap(target)) {
      // Map
      target.set(field, value);
    } else {
      // Object/Array
      target[field] = value;
    }
  } else {
    // Boxed Value
    target.set(value);
  }
}

function defaultIsValid(target, field) {
  if (field) {
    if (!isObservableMap(target)) {
      // Object/Array
      const error = target[camelCase('validateError', field)];
      if (error) {
        return ['error', error.message];
      }
    }
  }
  if (getField(target, field)) {
    return ['success'];
  }
  return [];
}

@observer
export class Input extends React.Component{
  onChange = e => {
    const { value } = e.target;
    const { target, field } = this.props;
    setField(target, field, value);
  };

  render() {
    const {
      target, field, isValid = defaultIsValid,
      label,
      placeholder,
    } = this.props;

    const [state, help] = isValid(target, field);

    return (
      <Form.Item
        label={label}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        validateStatus={state}
        help={help}
      >
        <AntdInput
          placeholder={placeholder}
          value={getField(target, field)}
          onChange={this.onChange}
        />
      </Form.Item>
    )
  }
}

@observer
export class InputNumber extends React.Component{
  onChange = value => {
    const { target, field } = this.props;
    setField(target, field, value);
  };

  render() {
    const {
      target, field, isValid = defaultIsValid,
      label,
      placeholder,
      min, max, step,
    } = this.props;

    const [state, help] = isValid(target, field);

    return (
      <Form.Item
        label={label}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        validateStatus={state}
        help={help}
      >
        <AntdInputNumber
          placeholder={placeholder}
          value={getField(target, field)}
          min={min}
          max={max}
          step={step}
          onChange={this.onChange}
        />
      </Form.Item>
    )
  }
}

const uploadConfig = observable({
  url: null,
  formData: null,
  fieldName: null,
});

async function refreshUploadConfig(){
  const { url, formData, fieldName } = await get('/auploadfile');
  runInAction(()=>{
    uploadConfig.url = url;
    uploadConfig.formData = formData;
    uploadConfig.fieldName = fieldName;
  });
}

setTimeout(refreshUploadConfig, 1000);
setInterval(refreshUploadConfig, 30*60*1000);

@observer
export class UploadImage extends React.Component {
  onChange = e => {
    const { value } = e.target;
    const { target, field } = this.props;
    setField(target, field, value);
  };

  @observable
  fileList = getField(this.props.target, this.props.field) ? [{
    uid: -1,
    url: `http://oalpta27j.bkt.clouddn.com/${getField(this.props.target, this.props.field)}`,
    status: 'done',
    thumbUrl: `http://oalpta27j.bkt.clouddn.com/${getField(this.props.target, this.props.field)}?imageView2/1/w/150/h/150`,
  }] : [];

  onChange = ({file}) => {
    if (file.response) {
      const {
        target, field,
      } = this.props;
      const { hash } = file.response;
      setField(target, field, hash);
      file.response = null;
      file.url = `http://oalpta27j.bkt.clouddn.com/${hash}`;
      file.thumbUrl = `http://oalpta27j.bkt.clouddn.com/${hash}?imageView2/1/w/150/h/150`;
    } else {
      setField(target, field, '');
    }
    this.fileList.replace([file]);
  }

  createData = file => ({
    ...uploadConfig.formData,
    [uploadConfig.fieldName]: file,
  });

  renderUploader() {
    const {
      target, field,
    } = this.props;
    if (!uploadConfig.url) {
      return;
    }
    // const value = getField(target, field);

    return (
      <AntdUpload.Dragger
        action={uploadConfig.url}
        data={this.createData}
        value={getField(target, field)}
        fileList={this.fileList.slice(0)}
        onChange={this.onChange}
        listType="picture-card"
      >
        <Button>上传</Button>
      </AntdUpload.Dragger>
    );
  }

  render() {
    const {
      target, field, isValid = defaultIsValid,
      label,
    } = this.props;

    const [state, help] = isValid(target, field);

    return (
      <Form.Item
        label={label}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        validateStatus={state}
        help={help}
      >
        {this.renderUploader()}
      </Form.Item>
    )
  }
}